<template>
  <div style="height: 100%">
    <div class="container" style="height: 100%">
      <div>
        <div class="balance">
          <div>
            <div>
              <p class="fw">充值余额</p>
              <p class="fs_24 fw">{{ balance_info?.amount }}</p>
            </div>
            <div
              class="detail"
              @click="
                router.push({ name: 'recharge_detail' }),
                  EventBus.emit('change_default_active', '/recharge_detail')
              "
            >
              明细
            </div>
          </div>
        </div>
        <div class="title m_top30">本次充值套餐</div>
        <div style="margin: 15px 10px" class="flex">
          <el-input
            disabled
            placeholder="请选择"
            style="width: 300px"
            :value="
              choose_item_name == ''
                ? ''
                : choose_item_name + ' (起充金额：' + minAmount + ' )'
            "
            class="choose_item_name"
          ></el-input>
          <el-button
            type="primary"
            class="m_left5"
            @click="(show_sclect_box = true), (select_index = 0);"
            >选择套餐</el-button
          >
        </div>
        <div class="title m_top30">充值金额（元）</div>
        <div style="margin: 15px 10px">
          <el-input
            :placeholder="choose_item_name == '' ? '请优先选择套餐' : '请输入'"
            :disabled="choose_item_name == '' ? true : false"
            style="width: 300px"
            v-model="form_data.rechargeAmount"
            @input="
              form_data.rechargeAmount = form_data.rechargeAmount.replace(
                /^(0+)|[^\d]+/g,
                ''
              )
            "
            @blur="get_money"
            show-word-limit
            maxlength="9"
          ></el-input>
          <!-- <div class="info_1">
            实际应付：<span>￥{{ money_list[0] }}</span> 额外赠送：<span
              >￥{{ money_list[1] }}</span
            >实得：<span>￥{{ money_list[2] }}</span>
          </div>
          <el-button>其他待付</el-button> -->
        </div>
        <div class="title m_top30">支付方式</div>
        <div class="pay_way">
          <div
            v-for="(item, index) in pay_way_list"
            :key="index"
            @click="form_data.payWay = index + 2"
            :class="form_data.payWay == index + 2 ? 'select_pay_way' : ''"
          >
            <svgBtn :icon="item.icon" style="font-size: 24px"></svgBtn>
            <span>{{ item.name }}</span>
            <svgBtn
              class="select_top_right"
              icon="select_top_right"
              style="font-size: 22px"
              v-if="form_data.payWay == index + 2"
            ></svgBtn>
          </div>
        </div>
        <div class="title m_top30">转账信息</div>
        <div style="margin: 15px 10px" class="info_2">
          收款公司名：<span>{{ collection_info?.company }}</span> 收款账号：<span
            ><span v-for="item in collection_info?.cardNumber" style="margin: 0">{{
              item
            }}</span></span
          >
          开户行名称：<span>{{ collection_info?.bank }}</span>
        </div>
        <div class="title m_top30">付款附言</div>
        <el-input
          type="textarea"
          resize="none"
          :autosize="{ minRows: 2, maxRows: 6 }"
          style="margin: 15px 10px"
          v-model="form_data.remark"
          show-word-limit
          maxlength="300"
        ></el-input>
        <div class="recharge" v-if="role_list[0].has_role">
          <el-button
            type="primary"
            class="fs_16"
            style="width: 220px; height: 50px"
            @click="to_pay"
            >支付</el-button
          >
        </div>
      </div>
      <div class="flex_cm m_left20 flex1">
        <div class="fw p_15_0 fs_16">付款须知</div>
        <div class="main_box">
          <div class="notice" v-html="notice"></div>
          <div class="checkbox">
            <el-checkbox v-model="agree">本人已全面了解并同意以上约定</el-checkbox>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="show_sclect_box"
      direction="rtl"
      size="80%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <template #title>
        <h4>套餐选择</h4>
      </template>
      <template #default>
        <div class="taocan_box">
          <div
            v-for="(item, index) in select_list"
            @click="select_taocan({ item: item, index: index })"
            :class="select_index == index ? 'select' : ''"
          >
            {{ item.name }}
            <svgBtn
              class="select_top_right flex_cc"
              icon="select_top_right"
              style="font-size: 22px"
              v-if="select_index == index"
            ></svgBtn>
          </div>
        </div>
        <el-table
          border
          style="text-align: center; margin-top: 15px"
          :data="select_info?.rechargePackageStageList"
        >
          <el-table-column label="序号" type="index" width="80px"></el-table-column>
          <el-table-column label="起始点数" prop="startAmount"> </el-table-column>
          <el-table-column label="结束点数" prop="endAmount"> </el-table-column>
          <el-table-column
            v-for="(item, index) in table_enterprice_list"
            :key="index"
            :label="item.name"
          >
            <el-table-column label="充值折扣（%）">
              <template #default="scope: any">
                <div
                  :style="{
                    color: item.id == current_enterprise_level ? '#3580eb' : '',
                  }"
                >
                  {{ scope.row.rechargePackageStageLevelList[index]?.discount }}
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="额外赠送比例（%）">
              <template #default="scope:any">
                <div
                  :style="{
                    color: item.id == current_enterprise_level ? '#3580eb' : '',
                  }"
                >
                  {{ scope.row.rechargePackageStageLevelList[index]?.give }}
                </div>
              </template>
            </el-table-column> -->
          </el-table-column>
          <el-table-column label="备注">
            <template #default="scope: any">
              <div>{{ scope.row.remark }}</div>
            </template>
          </el-table-column>
        </el-table>
        <div class="p_15 m_top20" style="background-color: #f5f6f7">
          <div class="flex_js m_bottom5">
            <div class="fw">套餐介绍</div>
            <div class="upgrade" v-if="current_enterprise_level == 2" @click="upgrade">
              升级为签约企业
            </div>
          </div>
          <div>{{ select_info?.introduce }}</div>
        </div>
        <el-divider></el-divider>
        <div class="tr m_top10">
          <el-button @click="show_sclect_box = false">取消</el-button>
          <el-button type="primary" @click="choose">选择</el-button>
        </div>
      </template>
    </el-drawer>
    <pay_box_page
      :pay_box="pay_box"
      :form_data="form_data"
      :again_pay_form_data="[]"
    ></pay_box_page>
  </div>
</template>

<script lang="ts" setup>
import { check_role } from "@/utils/check_role";
import { ref, onMounted, computed } from "vue";
import svgBtn from "@/components/svg_button.vue";
import pay_box_page from "./pay_box.vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import { ElMessage, ElMessageBox } from "element-plus";
// import upload from '@/view/components/upload.vue'
import store from "@/store";
import EventBus from "@/utils/EventBus";
import { useRouter } from "vue-router";
const router = useRouter();
const role_list = ref([{ path: "recharge/post", has_role: false }]);
const upgrade = () => {
  ElMessageBox.confirm("请前往官网升级页面进行升级", "", {
    confirmButtonText: "立即前往",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    type: "warning",
  })
    .then(() => {
      window.location.href = window.location.host == "localhost:8081" ? "/#" : "/home/#";
    })
    .catch(() => {});
};
EventBus.on("close_pay_box", () => {
  pay_box.value = false;
  pay_form_index.value = 0;
  //   pay_form_data.value = []
  //   pay_form_data.value.push(pay_form_data_item)
});
const show_sclect_box = ref(); // 套餐选择框
const select_index = ref(0); // 套餐选择值
const select_list = ref(); // 套餐列表
const select_info = ref(); // 选择的套餐详情
const choose_item_name = ref(""); // 选择的套餐名称
const minAmount = ref(); // 套餐最低充值金额
const maxAmount = ref(); // 套餐最低充值金额
const notice = ref(); // 充值须知
const pay_way_list = ref([
  // 支付方式
  { icon: "weixin", name: "微信支付" },
  { icon: "zhifubao", name: "支付宝支付" },
  { icon: "bank_card", name: "银行卡支付" },
]);
const money_list = ref([]); // 根据套餐优惠计算 金额的详细信息
const pay_box = ref(false); // 支付弹窗
const agree = ref(false); // 支付须知
const form_data = ref({
  // 创建订单数据
  remark: "",
  rechargePackageId: "",
  payWay: 4, // 1 余额支付 2 微信 3 支付宝  4 银行卡
  rechargeAmount: "",
});
const current_enterprise_level = computed(() => {
  // 当前企业登等级  取多产品中最高级  计算优惠时用到
  return Math.max(...store.state.current_enterprise_level.map(({ levelId }) => levelId));
});
const pay_form_data_item = {
  // 银行卡支付 提交表单数据原
  outTradeNo: "",
  payBank: "",
  payMessage: "",
  payPic: [],
  payer: "",
  totalFee: "",
};
// const pay_form_data = ref([JSON.parse(JSON.stringify(pay_form_data_item))]) // 银行卡支付 提交数据列表
const pay_form_index = ref(0); // 银行卡支付 第几笔
onMounted(() => {
  role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  get_select_list();
  get_enterprise_level_list();
  get_collection_info();
});
const to_pay = () => {
  if (form_data.value.rechargeAmount == "") {
    ElMessage.warning("请输入充值金额！");
    return;
  } else if (form_data.value.rechargeAmount < minAmount.value) {
    ElMessage.warning("充值金额不得小于套餐起充金额");
    return;
  } else if (form_data.value.rechargeAmount > maxAmount.value) {
    ElMessage.warning("充值金额不得大于套餐最大金额");
    return;
  } else if (!agree.value) {
    ElMessage.warning("请同意付款须知！");
    return;
  }
  pay_box.value = true;
};
const balance_info = ref(
  computed(() => {
    return store.state.balance_info;
  })
);
const collection_info = ref();
const get_collection_info = () => {
  axios
    .request({ url: serviceApi.collection_info, method: "get" })
    .then((res) => {
      console.log(res);
      collection_info.value = res.data[0];
      collection_info.value.cardNumber = collection_info.value.cardNumber.split("");
      for (let i in collection_info.value.cardNumber) {
        if (parseInt(i) > 1 && (parseInt(i) + 1) % 5 == 0) {
          collection_info.value.cardNumber.splice(i, 0, " ");
        }
      }
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
const choose = () => {
  console.log(select_info.value);
  form_data.value.rechargePackageId = select_info.value.id;
  choose_item_name.value = select_info.value.name;
  minAmount.value = select_info.value.rechargePackageStageList[0].startAmount;
  maxAmount.value = select_info.value.rechargePackageStageList.at(-1).endAmount;
  notice.value = select_list.value[select_index.value].notice;
  form_data.value.rechargeAmount = "";
  money_list.value = [];
  show_sclect_box.value = false;
};
const get_money = (e) => {
  console.log(e.target.value);
  if (!/(^[1-9]\d*$)/.test(e.target.value)) {
    ElMessage.warning("请输入正整数");
    form_data.value.rechargeAmount = "";
    return;
  } else {
    let discount = 0;
    let give = 0;
    var list = select_info.value.rechargePackageStageList;
    let test_money = list.some((item) => {
      return (
        parseInt(item.startAmount) <= parseInt(form_data.value.rechargeAmount) &&
        parseInt(form_data.value.rechargeAmount) <= parseInt(item.endAmount)
      );
    });
    if (!test_money) {
      ElMessage.error("输入金额不在所选套餐的价格区间内，请重新输入");
      form_data.value.rechargeAmount = "";
      return;
    }
    for (let i in list) {
      if (
        parseInt(list[i].startAmount) <= parseInt(form_data.value.rechargeAmount) &&
        parseInt(form_data.value.rechargeAmount) <= parseInt(list[i].endAmount)
      ) {
        for (let ii in list[i].rechargePackageStageLevelList) {
          if (
            list[i].rechargePackageStageLevelList[ii].levelId ==
            current_enterprise_level.value
          ) {
            discount = list[i].rechargePackageStageLevelList[ii].discount;
            give = list[i].rechargePackageStageLevelList[ii].give;
          }
        }
      }
    }
    console.log(discount, give);
    money_list.value[0] =
      (parseInt(form_data.value.rechargeAmount) * (discount ? discount : 0)) / 100;
    money_list.value[1] =
      (parseInt(form_data.value.rechargeAmount) * (give ? give : 0)) / 100;
    money_list.value[2] =
      (parseInt(form_data.value.rechargeAmount) * (give ? give : 0)) / 100 +
      parseInt(form_data.value.rechargeAmount);
  }
};
const select_taocan = (e) => {
  select_index.value = e.index;
  get_select_list_info(e.item.id);
  select_enterprise_level(e.item.levelIdList);
};
const get_select_list = () => {
  axios
    .request({
      url: serviceApi.rechargePackage_list,
      method: "post",
      data: {
        current: 1,
        pageSize: 100,
        status: 2,
        effectStatus: 1,
        levelId: current_enterprise_level.value,
      },
    })
    .then((res) => {
      console.log(res);
      select_list.value = res.data.content;
      if (res.data.content.length != 0) {
        get_select_list_info(res.data.content[0].id);
        select_enterprise_level(res.data.content[0].levelIdList);
      }
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
const get_select_list_info = (e) => {
  axios
    .request({ url: serviceApi.rechargePackage_curd + "/" + e, method: "get" })
    .then((res) => {
      console.log(res.data);
      select_info.value = res.data;
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
const table_enterprice_list = ref();
const select_enterprise_level = (e) => {
  console.log(e);
  table_enterprice_list.value = [];
  for (let i in enterprise_level_list.value) {
    if (e.indexOf(enterprise_level_list.value[i].id) != -1) {
      table_enterprice_list.value.push(enterprise_level_list.value[i]);
    }
  }
  console.log(table_enterprice_list.value);
};
const enterprise_level_list = ref();
const get_enterprise_level_list = () => {
  axios
    .request({
      url: serviceApi.enterprise_level_list,
      method: "post",
    })
    .then((res) => {
      enterprise_level_list.value = res.data;
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
</script>

<style lang="scss" scoped>
.choose_item_name {
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
.notice {
  height: 100%;
  width: 100%;
  overflow-y: scroll;
  text-align: justify;
  box-sizing: border-box;
  padding: 16px;
  >>> p {
    color: #333;
    line-height: 28px;
  }
}

.upgrade {
  padding: 0 15px;
  text-align: center;
  height: 32px;
  line-height: 32px;
  font-size: 12px;
  color: #3580eb;
  border: 1px solid #3580eb;
  border-radius: 2px;
}
.taocan_box {
  display: flex;
  align-items: center;
  > div {
    margin-right: 20px;
    height: 48px;
    line-height: 48px;
    padding: 0 20px;
    font-size: 16px;
    position: relative;
    font-weight: bold;
    border: 1px solid #c3c3c3;
    border-radius: 2px;
  }
  .select {
    background-color: #f0f6ff;
    border-color: #3580eb;
  }
  .select_top_right {
    position: absolute;
    top: -1px;
    right: -1px;
    height: 22px;
    line-height: 22px;
  }
}
.main_box {
  flex: 1;
  border: 1px solid #e8eaed;
  overflow-y: hidden;
  padding: 10px 10px 60px 10px;
  margin-bottom: 15px;
  position: relative;
  .checkbox {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 50px;
    line-height: 50px;
    background-color: #fff;
    text-align: center;
  }
}
.info_1 {
  margin: 16px 0;
  span {
    font-size: 20px;
    font-weight: bold;
    color: #3580eb;
    margin-right: 20px;
  }
}
.info_2 {
  color: #999999;
  span {
    color: #333;
    margin-right: 20px;
  }
}
.pay_way {
  display: flex;
  align-items: baseline;
  margin: 15px 10px;
  > div {
    margin-right: 30px;
    border: 1px solid #c3c3c3;
    height: 50px;
    padding: 0 15px;
    display: flex;
    align-items: center;
    position: relative;
    border-radius: 2px;
    cursor: pointer;
    span {
      margin-left: 6px;
    }
  }
  .select_pay_way {
    background-color: #f0f6ff;
    border: 1px solid #3580eb;
  }
  .select_top_right {
    position: absolute;
    top: -1px;
    right: -1px;
    height: 22px;
    line-height: 22px;
  }
}
.balance {
  display: flex;
  align-items: center;
  margin-top: 30px;
  > div {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 160px;
    padding: 0 15px;
    height: 90px;
    color: #fff;
    margin-right: 30px;
    .detail {
      width: 44px;
      text-align: center;
      line-height: 24px;
      height: 24px;
      font-size: 12px;
      background: rgba(255, 255, 255, 0.32);
      border-radius: 2px;
      cursor: pointer;
    }
  }
  > div:first-child {
    background-image: url(@/assets/img/balance_1.png);
    background-size: 100% 100%;
  }
  > div:last-child {
    background-image: url(@/assets/img/balance_2.png);
    background-size: 100% 100%;
  }
}
.container {
  display: flex;
  align-items: center;
  > div {
    height: 100%;
    background-color: #fff;
  }
  > div:first-child {
    padding: 0 30px;
    position: relative;
    width: 800px;
    flex-shrink: 0;
  }
  > div:last-child {
    padding: 0 20px;
  }
}
.recharge {
  position: absolute;
  bottom: 10px;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
